package com.nurun.cacheimageloader;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;

public abstract class AbstractImageDownloader {

	protected static final String PROTOCOL_FILE = "file";
	protected static final String PROTOCOL_HTTP = "http";
	protected static final String PROTOCOL_HTTPS = "https";
	protected static final String PROTOCOL_FTP = "ftp";

	public InputStream getStream(URI imageUri) throws IOException {
		String scheme = imageUri.getScheme();
		if (PROTOCOL_HTTP.equals(scheme) || PROTOCOL_HTTPS.equals(scheme) || PROTOCOL_FTP.equals(scheme)) {
			return getStreamFromNetwork(imageUri);
		} else if (PROTOCOL_FILE.equals(scheme)) {
			return getStreamFromFile(imageUri);
		} else {
			return getStreamFromOtherSource(imageUri);
		}
	}

	protected InputStream getStreamFromOtherSource(URI imageUri) throws IOException {
		return null;
	}

	protected abstract InputStream getStreamFromNetwork(URI imageUri) throws IOException;

	protected InputStream getStreamFromFile(URI imageUri) throws IOException {
		return new BufferedInputStream(imageUri.toURL().openStream());
	}

	public static AbstractImageDownloader createDefault() {
		return new ImageDownloaderFromNetwork();
	}
}